package com.haier.npt.security.api;

import java.util.Set;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.haier.npt.common.JsonResult;
import com.haier.npt.security.cache.SysPermissionCacheService;
import com.haier.npt.security.domain.SysPermission;
import com.haier.npt.security.dto.RequestInfoDTO;
import com.haier.npt.security.event.UserPermissionChangeEvent;
import com.haier.npt.security.resource.SysPermissionResource;
import com.haier.npt.security.service.SysPermissionService;


/**
 * @Description:权限项维护
 * @author: lixu
 * @date:   2018年7月13日 下午2:09:00   
 */
@RestController
public class SysPermissionController implements SysPermissionResource, ApplicationContextAware {

    @Autowired
    private SysPermissionService sysPermissionService;

    private ApplicationContext conext;

    @Autowired
    private SysPermissionCacheService sysPermissionCacheService;

    /**
     * 添加一个权限项
     */
    @Override
    @RequestMapping(value = "/permissions/add", method = RequestMethod.POST)
    public JsonResult<Boolean> addPermission(
            @RequestBody @Valid SysPermission sysPermission) {
        boolean result = this.sysPermissionService.addPermission(sysPermission);
        if (result) {
            this.conext.publishEvent(new UserPermissionChangeEvent(this));
        }
        return JsonResult.success(result);
    }

    /**
     * 根据权限项编号删除权限项
     */
    @Override
    @RequestMapping(value = "/permissions/{permissionId}/delete", method = RequestMethod.POST)
    public JsonResult<Boolean> delPermissionById(
            @RequestParam(required = true) Long id) {
        boolean result = this.sysPermissionService.deletePermissionById(id);
        if (result) {
            this.conext.publishEvent(new UserPermissionChangeEvent(this));
        }
        return JsonResult.success(result);
    }

    /**
     * 根据url和serviceid 查询
     *
     * @param requestInfoDTO
     * @return
     */
    @Override
    @RequestMapping(value = "/internal/permissions/percode", method = RequestMethod.POST)
    public JsonResult<Set<String>> getPermissionCode(@RequestBody RequestInfoDTO requestInfoDTO) {
    	//this.conext.publishEvent(new UserPermissionChangeEvent(this));
        //这里加缓存
        return JsonResult.success(sysPermissionCacheService.getPermissionCode(requestInfoDTO));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        conext = applicationContext;
    }

}
